package com.adee.netty.websocket;

import com.adee.netty.groupchat.GroupChatServerHeartBeatHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class WebsocketServer {
    private int port;
    public WebsocketServer(int port) {
        this.port = port;
    }
    public static void main(String[] args) {
        new WebsocketServer(7000).run();
    }
    public void run() {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    // handler发生在连接初始化的时候，childHandler发生在连接建立好之后
                    .handler(new LoggingHandler(LogLevel.ERROR))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 获取到pipeLine
                            ChannelPipeline pipeline = ch.pipeline();
                            // 加入一个心跳检测handler
                            pipeline.addLast(new IdleStateHandler(30, 50, 170, TimeUnit.SECONDS));
                            // 加入一个对空闲检测进一步处理的自定义handler
                            pipeline.addLast(new GroupChatServerHeartBeatHandler());
                            // websocket协议基于http协议，使用http编解码器
                            pipeline.addLast(new HttpServerCodec());
                            // 以块方式写
                            pipeline.addLast(new ChunkedWriteHandler());
                            // http发送数据量很大时，就会分段发送，需要聚合恢复原数据
                            pipeline.addLast(new HttpObjectAggregator(8192));
                            /*
                             * 对应websocket，它的数据是以帧（frame）形式传送
                             * 浏览器请求url：ws://localhost:7000/hello
                             * WebSocketServerProtocolHandler 核心功能是将http协议升级为ws协议，保持长连接
                             * */
                            pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
                            // 处理业务逻辑
                            pipeline.addLast(new WebsocketServerHandler());
                        }
                    });
            System.out.println("netty 服务器已启动，port=" + port);
            ChannelFuture future = bootstrap.bind(port).sync();
            // 阻塞监听关闭
            future.channel().closeFuture().sync();
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
